using Microsoft.EntityFrameworkCore;
using MyHomeworkWebAPi.Models.DTOs;
using MyHomeworkWebAPi.Models.ef;
using MyHomeworkWebAPi.Models.Request;
using System.Text.RegularExpressions;

namespace MyHomeworkWebAPi.Services
{
    /// <summary>
    /// 商品服务实现类
    /// </summary>
    public class ProductServices : IProductServices
    {
        private readonly SecondHandTradingPlatformContext _context;

        /// <summary>
        /// 构造函数，注入数据库上下文
        /// </summary>
        /// <param name="context">数据库上下文</param>
        public ProductServices(SecondHandTradingPlatformContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 获取所有商品
        /// </summary>
        public async Task<List<ProductDTO>> GetAllAsync()
        {
            var products = await _context.Products
                .Include(p => p.User)
                .Include(p => p.Category)
                .OrderByDescending(p => p.ProductId)
                .ToListAsync();

            return products.Select(p => ProductDTO.FromProduct(p)).ToList();
        }

        /// <summary>
        /// 根据ID获取商品
        /// </summary>
        public async Task<ProductDTO> GetByIdAsync(Guid id)
        {
            var product = await _context.Products
                .Include(p => p.User)
                .Include(p => p.Category)
                .FirstOrDefaultAsync(p => p.ProductId == id);

            return ProductDTO.FromProduct(product);
        }

        /// <summary>
        /// 创建商品
        /// </summary>
        public async Task<ProductDTO> CreateAsync(Guid userId, ProductCreateRequest request)
        {
            // 验证商品类别是否存在
            var category = await _context.ProductCategories.FindAsync(request.CategoryId);
            if (category == null)
            {
                throw new Exception("商品类别不存在");
            }

            byte[] imageBytes = null;
            if (!string.IsNullOrEmpty(request.ImageBase64))
            {
                // 移除Base64字符串中的Data URI前缀（如果存在）
                string base64Data = Regex.Replace(request.ImageBase64, @"^data:image\/[a-zA-Z]+;base64,", "");
                imageBytes = Convert.FromBase64String(base64Data);
            }

            var product = new Product
            {
                ProductId = Guid.NewGuid(),
                UserId = userId,
                Title = request.Title,
                Price = request.Price,
                CategoryId = request.CategoryId,
                Description = request.Description,
                Image = imageBytes ?? Array.Empty<byte>(),
                Status = "在售" // 新创建的商品默认状态为"在售"
            };

            await _context.Products.AddAsync(product);
            await _context.SaveChangesAsync();

            // Load the user information
            await _context.Entry(product)
                .Reference(p => p.User)
                .LoadAsync();

            await _context.Entry(product)
                .Reference(p => p.Category)
                .LoadAsync();

            return ProductDTO.FromProduct(product);
        }

        /// <summary>
        /// 更新商品状态
        /// </summary>
        public async Task<ProductDTO> UpdateStatusAsync(Guid productId, string status)
        {
            var product = await _context.Products
                .Include(p => p.User)
                .Include(p => p.Category)
                .FirstOrDefaultAsync(p => p.ProductId == productId);

            if (product == null)
            {
                throw new Exception("商品不存在");
            }

            product.Status = status;
            await _context.SaveChangesAsync();

            return ProductDTO.FromProduct(product);
        }

        /// <summary>
        /// 获取用户发布的商品
        /// </summary>
        public async Task<List<ProductDTO>> GetByUserIdAsync(Guid userId)
        {
            var products = await _context.Products
                .Include(p => p.User)
                .Include(p => p.Category)
                .Where(p => p.UserId == userId)
                .OrderByDescending(p => p.ProductId)
                .ToListAsync();

            return products.Select(p => ProductDTO.FromProduct(p)).ToList();
        }

        /// <summary>
        /// 根据分类获取商品
        /// </summary>
        public async Task<List<ProductDTO>> GetByCategoryAsync(Guid categoryId)
        {
            var products = await _context.Products
                .Include(p => p.User)
                .Include(p => p.Category)
                .Where(p => p.CategoryId == categoryId)
                .ToListAsync();

            return products.Select(p => ProductDTO.FromProduct(p)).ToList();
        }

        /// <summary>
        /// 搜索商品
        /// </summary>
        public async Task<List<ProductDTO>> SearchAsync(string keyword)
        {
            var products = await _context.Products
                .Include(p => p.User)
                .Include(p => p.Category)
                .Where(p => p.Title.Contains(keyword) || 
                           p.Description.Contains(keyword) || 
                           p.Category.Name.Contains(keyword))
                .OrderByDescending(p => p.ProductId)
                .ToListAsync();

            return products.Select(p => ProductDTO.FromProduct(p)).ToList();
        }

        /// <summary>
        /// 删除商品
        /// </summary>
        public async Task<bool> DeleteAsync(Guid productId)
        {
            var product = await _context.Products.FindAsync(productId);
            if (product == null)
            {
                return false;
            }

            _context.Products.Remove(product);
            await _context.SaveChangesAsync();
            return true;
        }

        /// <summary>
        /// 更新商品信息
        /// </summary>
        public async Task<ProductDTO> UpdateAsync(Guid productId, ProductCreateRequest request)
        {
            var product = await _context.Products
                .Include(p => p.User)
                .Include(p => p.Category)
                .FirstOrDefaultAsync(p => p.ProductId == productId);

            if (product == null)
            {
                throw new Exception("商品不存在");
            }

            // 验证商品类别是否存在
            var category = await _context.ProductCategories.FindAsync(request.CategoryId);
            if (category == null)
            {
                throw new Exception("商品类别不存在");
            }

            // 更新商品信息
            product.Title = request.Title;
            product.Price = request.Price;
            product.Description = request.Description;
            product.CategoryId = request.CategoryId;

            // 如果提供了新的图片，则更新图片
            if (!string.IsNullOrEmpty(request.ImageBase64))
            {
                string base64Data = Regex.Replace(request.ImageBase64, @"^data:image\/[a-zA-Z]+;base64,", "");
                product.Image = Convert.FromBase64String(base64Data);
            }

            await _context.SaveChangesAsync();
            return ProductDTO.FromProduct(product);
        }
    }
} 